<template>
  <page-layout>
    <a-row :gutter="[10, 10]">
      <a-col :span="24">
        <a-card>
          <a-form ref="formRef" :model="modelForm.data" :labelCol="{ span: 9 }">
            <a-row>
              <a-col :span="8">
                <a-form-item
                  :label="t('teaching.label.tmName')"
                  name="tmName"
                  :rules="[{ required: true, message: '请输入教材名称' }]"
                >
                  <a-input v-model:value="modelForm.data.tmName" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('teaching.label.authorName')"
                  name="authorName"
                >
                  <a-input v-model:value="modelForm.data.authorName" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('teaching.label.edition')"
                  name="edition"
                >
                  <a-input v-model:value="modelForm.data.edition" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-item
                  :label="t('teaching.label.press')"
                  ref="press"
                  name="press"
                >
                  <a-input v-model:value="modelForm.data.press" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('teaching.label.downloadAddress')"
                  ref="downloadAddress"
                  name="downloadAddress"
                >
                  <a-input v-model:value="modelForm.data.downloadAddress" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('teaching.label.tmIsbn')"
                  ref="tmIsbn"
                  name="tmIsbn"
                >
                  <a-input v-model:value="modelForm.data.tmIsbn" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="8">
                <a-form-item
                    :label="t('teaching.label.tmDesc')"
                    ref="tmDesc"
                    name="tmDesc"
                >
                  <a-input v-model:value="modelForm.data.tmDesc" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-card>

      </a-col>
    </a-row>
  </page-layout>
  <div class="save-b">
    <div class="f-b">
      <a-button type="primary" @click="handleSave">{{
          t("button.save")
        }}</a-button>
      <a-button class="ml-10" @click="handleBack">{{
          t("button.back")
        }}</a-button>
    </div>
  </div>
</template>

<script>

import { save, details, upload, dictionary, update } from "@/api/module/teaching-material";
import { useI18n } from "vue-i18n";

import { Form, message, modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { useRouter, useRoute } from 'vue-router'

import {defineComponent, reactive, toRaw, createVNode, onMounted, onActivated, ref} from "vue";
const useForm = Form.useForm;
export default defineComponent({
  components: {
  },

  setup() {
    const { t } = useI18n();
    const router = useRouter()
    const route = useRoute()
    const formRef = ref()

    const formState = reactive({
      universityVisible: false,
      sexList: []
    });
    const labelCol = { span: 3, offset: 12 };
    const wrapperCol = { span: 14 };
    let modelForm = reactive({
      data: {
        tmName: "",
        authorName: "",
        edition: "",
        press: "",
        tmIsbn: "",
        tmDesc: "",
        downloadAddress: ""
      }
    });
    const fileList = reactive([])
    const formRules = reactive({
      tmName: [{ required: true, message: "请输入教材名称" }],
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelForm.data,
      formRules
    );
    const openDialog = (type) => {
      formState[type] = true;
    };
    const handleChange = info => {
      const arr = info.fileList.filter(v => v.status !== 'error')
      if (arr&&arr.length) {
        modelForm.data.files = arr.map(item => {
          return {
            url: item.response?item.response.path||'':'',
            type: 2
          }
        })
      }
    }

    const closeDialog = (type) => {
      formState[type] = false;
    };

    const selectUniversity = (value) => {
      formState["universityVisible"] = false;
      if (value) {
        modelForm.data.schId = value.id
        modelForm.data.schName = value.name
      }
    };

    const handleUpload = data => {
      const formData = new FormData()
      formData.append('file', data.file)
      upload(formData).then(res => {
        if (res.code === 500) {
          message.error({ content: '上传附件失败' })
          data.onError()
        } else {
          data.onSuccess(res.data)
        }
      })
    }

    // 获取详情
    const getDetails = (id) => {
      details({id}).then((res) => {
        if (res.success) {
          modelForm.data = reactive({
            ...modelForm.data,
            ...res.data,
          });
        }
      });
    };

    const getDctionary = () => {
      return dictionary({}).then(res => {
        if (res.success) {
          formState.sexList = res.data;
        }
      })
    }

    // 保存
    const handleSave = () => {
      formRef.value.validate().then(() => {
        const result = toRaw(modelForm.data);
        if (route.query.id) {
          editItem(result)
        } else {
          addItem(result)
        }
        formRef.value.resetFields()
      });
    };

    const editItem = (data) => {
      update(data).then((res) => {
        if (res.success) {
          message.success({ content: "编辑成功", duration: 1 }).then(() => {
            router.push({
              path: '/university/teaching-material'
            })
          });
        } else {
          message.warning({ content: "编辑成功", duration: 1 });
        }
      }).catch(err => {
        message.warning({ content: "编辑成功", duration: 1 });
      });
    }

    const addItem = (data) => {
      save(data).then((res) => {
        if (res.success) {
          message.success({ content: "保存成功", duration: 1 }).then(() => {
            router.push({
              path: '/university/teaching-material'
            })
          });
        } else {
          message.warning({ content: "保存失败", duration: 1 });
        }
      }).catch(err => {
        message.warning({ content: "保存失败", duration: 1 });
      });
    }

    const handleBack = () => {
      modal.confirm({
        title: '确定返回吗？',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '确定',
        cancelText: '取消',
        onOk() {
          router.push({
            path: '/university/teaching-material'
          })
        }
      })
    }

    onActivated(() => {
      formRef.value.resetFields()
      if (route.query.id) {
        getDetails(route.query.id);
      }
      getDctionary()
    })

    return {
      t,
      formRef,
      modelForm,
      formRules,
      labelCol,
      wrapperCol,
      openDialog,
      formState,
      handleChange,
      selectUniversity,
      closeDialog,
      handleSave,
      handleBack,
      validateInfos,
      resetFields,
      handleUpload,
      fileList,
    };
  },
});
</script>

<style lang="less" scoped>
.page-head {
  /deep/ .ant-page-header-heading-title {
    color: #2d8cf0;
  }
}

.pre-title {
  padding: 10px 25px;
  background-color: #f5f5f5;
  color: #555;
}

.up-file {
  width: 65%;
  display: flex;
  flex-wrap: nowrap;
  .label {
    width: 65px !important;
    line-height: 30px;
  }
  span:last-child {
    margin-left: 5px;
  }
}

.save-b {
  width: 100%;
  position: absolute;
  bottom: 0px;
  right: 20px;
  height: 50px;
  line-height: 50px;
  z-index: 9;
  .f-b {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
